<script setup lang="ts">
import { addPatientAPI, editPatientAPI, getPatientInfoByIdAPI } from '@/api/patient';
import type { AddpatientParams } from '@/types/patient';
import { onLoad, onReady } from '@dcloudio/uni-app';
import { onMounted, ref } from 'vue';

const formData = ref<AddpatientParams>({
    name: '', // 患者姓名
    idCard: '', // 患者身份证号
    gender: 1, // 性别，1：男，0：女
    defaultFlag: 1, // 是否设置为默认患者
})

const getAddpatient = async () => {
  const res = await addPatientAPI(formData.value)
  console.log(res);
}
getAddpatient()

// 是否为默认就诊人
const onSwitchChange = (event: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = event.detail.value ? 1 : 0
}

const FormRules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      { pattern:/^(?:[\u4e00-\u9fa5·]{2,16})$/,errorMessage: '请输入中文名字' }
    ]
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写患者身份证号' },
      { pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,errorMessage:'请输入正确的身份证号'}
    ]
  },
  gender: {
    rules: [
      { required: true, errorMessage: '请选择性别' },
      {
        validateFunction(rule, value, data,callback) {
          const idCardNumber = formData.value.idCard.charAt(16)
          if (Number(idCardNumber) % 2 !== value) {
            callback('选择的性别与身份证中的性别不匹配')
          }
          // callback()
          return true
        }
      }
    ]
  }
})

const FormRef = ref<UniHelper.UniFormsInstance>()
const onSubmit = async () => {
  await FormRef.value?.validate?.()
  if (props.id) {
    // 编辑
    await editPatientAPI({
      ...formData.value,
      id: props.id // 确保 id 是可选属性
    })
  } else {
    // 添加
    await addPatientAPI(formData.value)
  }
  /* #ifdef H5 */
  window.history.back()
  /* #endif */

  /* #ifdef MP-WEIXIN */
  uni.navigateBack()
  /* #endif */
  
  uni.showToast({
    title: '保存成功',
    icon: 'success',
  })
}

// 页面获取参数-第一种
// onLoad((options) => {
//   console.log(options);
// })

// 5. 接收页面参写法2-更方便-第二种
const props = defineProps<{ id?: string }>()
console.log('页面级组件，可通过 props 接收页面参数', props)

onReady(() => {
  // 动态设置导航栏标题
  uni.setNavigationBarTitle({
    title:props.id ? '编辑患者' : '添加患者'
  })
})

const getPatientINfoById = async () => {
  if (props.id) {
    // 根据患者id获取详情
    const res = await getPatientInfoByIdAPI(props.id)
    formData.value = res.data
  }
}
getPatientINfoById()
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" :model="formData" :rules="FormRules" ref="FormRef">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch 
            :checked="formData.defaultFlag === 1" 
            @change="onSwitchChange"
            style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
      {{ formData }}
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './index.scss';
</style>